package feedback

import (
	"context"
	"strings"
	"time"

	"mall/service/recommended/api/internal/svc"
	"mall/service/recommended/api/internal/types"
	client "mall/service/recommended/common/gorseclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateFeedbackLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateFeedbackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateFeedbackLogic {
	return &CreateFeedbackLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateFeedbackLogic) CreateFeedback(req *types.FeedbackInfo) (resp *types.RowAffectedResp, err error) {
	if len(strings.TrimSpace(req.ItemId)) == 0 ||
		len(strings.TrimSpace(req.UserId)) == 0 ||
		len(strings.TrimSpace(req.FeedbackType)) == 0 {
		return &types.RowAffectedResp{}, nil
	}
	user, err := l.svcCtx.GorseClient.GetUser(l.ctx, req.UserId)
	if err != nil || len(strings.TrimSpace(user.UserId)) == 0 {
		return nil, err
	}

	item, err := l.svcCtx.GorseClient.GetItem(l.ctx, req.ItemId)
	if err != nil || len(strings.TrimSpace(item.ItemId)) == 0 {
		return nil, err
	}
	var feedback = []client.Feedback{
		{
			ItemId:       req.ItemId,
			UserId:       req.UserId,
			FeedbackType: req.FeedbackType,
			Timestamp:    time.Now().String(),
		},
	}
	res, err := l.svcCtx.GorseClient.InsertFeedback(l.ctx, feedback)
	if err != nil {
		return nil, err
	}
	return &types.RowAffectedResp{
		RowAffected: uint32(res.RowAffected),
	}, nil
}
